# -*- coding: utf-8 -*-
"""
装饰器
"""
import time
from Util.tools import log
from Util.date_helper import current_timestamp
from threading import Thread
import threading
from functools import wraps
from selenium.webdriver.common.action_chains import ActionChains

save_mutex = threading.Lock()


def async(func):
    """
    异步开线程调用
    :param func: 被修饰的函数
    :return:
    """
    def wrapper(*args, **kwargs):
        thr = Thread(target=func, args=args, kwargs=kwargs)
        thr.start()
    return wrapper


# 修改'测试用例函数'注释( 动态从ini中获取用例名称 )
def modify_func_doc(func):
    # @wraps(func)  # 不改变使用装饰器原有函数的结构(如__name__, __doc__)
    def wrapper(self, *args, **kwargs):
        """ 用例名称 """
        wrapper.__doc__ = self.case_name
        func(self=self, *args, **kwargs)
    return wrapper


def elapse_time(func):
    """
    计算方法耗时
    :param func: 被修饰的函数
    :return:
    """
    def wrapper(*args, **kwargs):
        st = current_timestamp()
        res = func(*args, **kwargs)
        et = current_timestamp()
        log.info("%s ELAPSE TIME: %s" % (func.__name__, (et-st)/1000.0))
        return res
    return wrapper


def thread_save(func):
    @wraps(func)
    def processed_res(*args, **kwargs):
        save_mutex.acquire()
        st = time.time()
        res = func(*args, **kwargs)
        et = time.time()
        save_mutex.release()
        log.info(u"%s: DONE %s" % (func.__name__, (et-st)))
        return res
    return processed_res


# def get_action_chains(func):
#     """
#         获取 ActionChains() 实例
#         备注：self.action_chains_yield(): 动作链 生成器 < browser_action.py >
#     """
#     def warp(self, *args, **kwargs):
#         for action_chains in self.action_chains_yield():
#             func(self=self, action_chains=action_chains, *args, **kwargs)
#     return warp
